package cn.b.sky.form.service.impl;

import cn.b.sky.common.exception.ImeException;
import cn.b.sky.common.model.BatchJobReport;
import cn.b.sky.common.model.Page;
import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import cn.b.sky.form.dao.SequenceDao;
import cn.b.sky.form.model.Sequence;
import cn.b.sky.form.model.condition.SequenceCondition;
import cn.b.sky.form.service.SequenceService;
import cn.b.sky.user.SecurityContextUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;

/**
 * 
 * <strong>Title : SequenceServiceImpl.java<br></strong>
 * <strong>Package : cn.b.sky.flowable.service.impl<br></strong>
 * <strong>Description : </strong>序列操作业务类实现<br> 
 * <strong>Create on : 2016-09-28 上午09:36:14<br></strong>
 * <p>
 * @author JunLin.Yang<br>
 * @version <strong>v1.0.0</strong>
 */
@Service("sequenceService")
public class SequenceServiceImpl implements SequenceService {

  private static final Logger LOGGER = LoggerFactory.getLogger(SequenceServiceImpl.class);

  @Resource
  private SequenceDao sequenceDao;

  @Override
  public int insertSequence(Sequence data) {
    if (null == data) {
      return 0;
    }
    return this.sequenceDao.insertSequence(data);
  }

  @Override
  public int updateSequence(Sequence data) {
    if (null == data) {
      return 0;
    }
    return this.sequenceDao.updateSequence(data);
//    long id=generateNextValue("1310", "AAA");
//    throw new RuntimeException("");
  }

  @Override
  public BatchJobReport deleteSequence(Sequence data) {
    if (null == data) {
      return new BatchJobReport("", "data is null", false);
    }
    return this.deleteSequenceByPrimaryKey(data.getSiteCode(), data.getSequenceCode());
  }
  
  @Override
  public BatchJobReport deleteSequenceByPrimaryKey(String siteCode, String sequenceCode) {
    String cause = "";
    Boolean success = true;
    try {
      if (1 > this.sequenceDao.deleteSequenceByPrimaryKey(siteCode, sequenceCode)) {
        success = false;
        cause = "";
      }
    } catch (Exception e) {
      LOGGER.error("{}", e);
      TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        // 外键删除已存在提示
        cause = LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
            SecurityContextUtil.getLanguageCode(), "dataBaseOperationPkFail.M")
            + LocaleResourceBundle.getCommonResourceLabel(SecurityContextUtil.getSiteCode(),
                SecurityContextUtil.getLanguageCode(), "notDelete.M");
      } else {
        cause = e.getMessage();
      }
      success = false;
    }
    return new BatchJobReport("", cause, success);
  }

  @Override
  public Sequence getSequenceByPrimaryKey(String siteCode, String sequenceCode) {
    return this.sequenceDao.getSequenceByPrimaryKey(siteCode, sequenceCode);
  }

  @Override
  public boolean existSequenceByPrimaryKey(String siteCode, String sequenceCode) {
    return this.sequenceDao.existSequenceByPrimaryKey(siteCode, sequenceCode);
  }

  @Override
  public Page selectSequencePageByCondition(SequenceCondition condition) {
    condition.setData(this.sequenceDao.selectSequencePageDataByCondition(condition));
    condition.setTotalCount(this.sequenceDao.getSequencesCountByCondition(condition));
    return condition;
  }

  @Override
  public long getSequencesCountByCondition(SequenceCondition condition) {
    return this.sequenceDao.getSequencesCountByCondition(condition);
  }

  @Override
  public synchronized Long generateNextValue(String siteCode, String sequenceCode) { 
    Sequence sequence = sequenceDao.getSequenceByPrimaryKey(siteCode, sequenceCode);
    if (sequence == null) {
      throw ImeException.newException("numberNotExist.M");
    }
    sequence.setNextValue(sequence.getNextValue()+1);
    sequenceDao.updateSequence(sequence); 
    return sequence.getNextValue();    
  }

}
